<?php

class RoomfeatureController extends CController
{
	public function actionIndex()
	{
		$this->setPageTitle('Фишки номера');
		
		$this->render('index');
	}
	
	public function actionGetdata()
	{
		$start = (intval($_GET['start']) >= 0) ? intval($_GET['start']) : 0;
		$limit = (intval($_GET['limit']) >= 0) ? intval($_GET['limit']) : 20;
		$sort  = in_array(strtolower($_GET['sort']), array('id', 'title')) ? strtolower($_GET['sort']) : 'title'; 
		$dir   = in_array(strtolower($_GET['dir']), array('asc', 'desc')) ? strtolower($_GET['dir']) : 'asc';
		$callback = $_GET['callback'];
		
		$records = RoomFeature::model()->criteria($sort, $dir, $start, $limit)->findAll();
		$count   = RoomFeature::model()->count();
		
		$this->renderPartial('json', array(
			'data'  => $records,
			'count' => $count,
			'callbackFunction' => $callback
		), false, true);
	}
	
	public function actionSave()
	{
		$title = $_POST['title'];
		
		if ($title != '') {
			$roomFeature = new RoomFeature();
			$roomFeature->title = $title;
			$roomFeature->save();
		}
		
		die('{success:true}');
	}
	
	public function actionUpdate()
	{
		$id    = intval($_GET['id']);
		$title = $_POST['title'];
		
		if ($title != '') {
			$feature = RoomFeature::model()->findByPk($id);
			$feature->title = $title;
			$feature->save();
			
			die("{success:true, title:'" . htmlspecialchars($title, ENT_QUOTES) . "'}");
		} else {
			die("{success:true, title:''}");			
		}
	}
	
	public function actionCheckhotels()
	{
		$id = intval($_GET['id']);
		
		$records = Hotel2roomFeature::model()
						->with(array('hotels'))
						->findAll('roomFeatureId=:roomFeatureId', array(':roomFeatureId' => $id));
		
		$hotels = array();
						
		if (count($records) > 0) {
			foreach ($records as $rec) {
				$connectedHotel = $rec->getRelated('hotels');
				
				if (isset($connectedHotel->id) && intval($connectedHotel->id) > 0) {
					 $hotels[] = array(
					 	'id'    => intval($connectedHotel->id),
					 	'title' => htmlspecialchars($connectedHotel->title, ENT_QUOTES)
					 );
				}
			}
		}
		
		$this->renderPartial('check', array(
			'hotels'  => $hotels
		), false, true);
	}
	
	public function actionRemove()
	{
		$id = intval($_GET['id']);

		if ($id > 0) {
			$feature = RoomFeature::model()->findByPk($id);
			$feature->delete();
			
			Hotel2roomFeature::model()->deleteAll('roomFeatureId=:roomFeatureId', array(':roomFeatureId' => $id));
		}
		
		die();
	}
}